<div class="mt-6 flex flex-row gap-4 mx-auto max-w-7xl">
    <div class="grow">
        <h1>Create Heroku resource</h1>
        <%= form_for @conn, Routes.heroku_path(@conn, :create), [], fn f -> %>
        <% uuid = Ecto.UUID.generate() %>
        <%= for field <- [
            %{id: :uuid, label: "Id (randomly generated)", value: uuid},
            %{id: :name, label: "Name", value: "heroku-app"},
            %{id: :plan, label: "Plan", value: "free"},
            %{id: :region, label: "Region", value: "us"},
            %{id: :callback_url, label: "Callback", value: "https://api.heroku.com/addons/#{uuid}"},
        ] do %>
            <div>
                <label class="block text-sm font-medium text-gray-700" for={field.id}><%= field.label %></label>
                <div class="mt-1">
                    <%= text_input f, field.id, value: field.value, placeholder: field.value, required: true, class: "block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm" %>
                    <%= error_tag f, field.id %>
                </div>
            </div>
        <% end %>
        <div class="pt-5">
            <%= submit "Create resource", id: "create-resource", class: "inline-flex justify-center py-2 px-4 border border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500" %>
        </div>
        <% end %>
        <script>
            const createResourceForm = document.querySelector('#create-resource').closest('form')
            createResourceForm.addEventListener('submit', (event) => {
                event.preventDefault()
                const form = event.target
                const data = Object.fromEntries(new FormData(form).entries())
                data.oauth_grant = { // not used, so add static data
                    code: 'c85cdb57-1037-4c68-a2a7-d759eb92dab1',
                    expires_at: '2016-03-03T18:01:31-0800',
                    type: 'authorization_code'
                }
                fetch(form.getAttribute('action'), {
                    method: form.getAttribute('method'),
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Basic ${btoa(`<%= @heroku.addon_id %>:<%= @heroku.password %>`)}`
                    },
                    body: JSON.stringify(data)
                }).then(res => res.json()).then(() => document.location.reload(true), err => console.error(err))
            })
        </script>
    </div>
    <div class="grow">
        <h1>Login with Heroku SSO</h1>
        <% resource = @resources |> List.first %>
        <%= form_for @conn, Routes.heroku_path(@conn, :login), [class: "login-form"], fn f -> %>
            <%= for field <- [
                %{id: :email, label: "Email", value: "user@mail.com"},
                %{id: :resource_id, label: "Resource id", value: resource.id},
                %{id: :app, label: "App name", value: resource.app},
                %{id: :timestamp, label: "Timestamp", value: System.os_time(:second)},
                %{id: :salt, label: "SSO Salt", value: @heroku.sso_salt},
                %{id: :resource_token, label: "Token", value: ""}
            ] do %>
                <div>
                    <label class="block text-sm font-medium text-gray-700" for={field.id}><%= field.label %></label>
                    <div class="mt-1">
                        <%= text_input f, field.id, value: field.value, placeholder: field.value, required: true, class: "block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm" %>
                        <%= error_tag f, field.id %>
                    </div>
                </div>
            <% end %>
            <div class="pt-5">
                <%= submit "Login", class: "inline-flex justify-center py-2 px-4 border border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500" %>
            </div>
        <% end %>
        <script>
            const loginForm = document.querySelector('.login-form')
            const app = document.querySelector('#app')
            const resourceId = document.querySelector('#resource_id')
            const timestamp = document.querySelector('#timestamp')
            const salt = document.querySelector('#salt')
            const resourceToken = document.querySelector('#resource_token')

            computeToken()
            resourceId.addEventListener('change', () => computeToken())
            timestamp.addEventListener('change', () => computeToken())
            salt.addEventListener('change', () => computeToken())

            async function computeToken() {
                resourceToken.value = await sha1(`${resourceId.value}:${salt.value}:${timestamp.value}`)
            }

            async function sha1(str) {
                const msgUint8 = new TextEncoder().encode(str)
                const hashBuffer = await crypto.subtle.digest('SHA-1', msgUint8)
                const hashArray = Array.from(new Uint8Array(hashBuffer))
                return hashArray.map(b => b.toString(16).padStart(2, '0')).join('')
            }
        </script>
    </div>
</div>
<div class="mt-6 max-w-7xl mx-auto">
    <h1>Heroku resources</h1>
    <table class="min-w-full divide-y divide-gray-300">
        <thead class="bg-gray-50">
            <tr>
                <th scope="col" class="whitespace-nowrap px-2 py-3.5 text-left text-sm font-semibold text-gray-900">Id</th>
                <th scope="col" class="whitespace-nowrap px-2 py-3.5 text-left text-sm font-semibold text-gray-900">Name</th>
                <th scope="col" class="whitespace-nowrap px-2 py-3.5 text-left text-sm font-semibold text-gray-900">App</th>
                <th scope="col" class="whitespace-nowrap px-2 py-3.5 text-left text-sm font-semibold text-gray-900">Plan</th>
                <th scope="col" class="whitespace-nowrap px-2 py-3.5 text-left text-sm font-semibold text-gray-900">Organization</th>
                <th scope="col" class="whitespace-nowrap px-2 py-3.5 text-left text-sm font-semibold text-gray-900">Projects</th>
                <th scope="col" class="whitespace-nowrap px-2 py-3.5 text-left text-sm font-semibold text-gray-900">Actions</th>
            </tr>
        </thead>
        <tbody class="divide-y divide-gray-200 bg-white">
            <%= for resource <- @resources do %>
                <tr>
                    <td class="whitespace-nowrap py-2 py-2 text-sm text-gray-900"><%= resource.id %></td>
                    <td class="whitespace-nowrap px-2 py-2 text-sm text-gray-900"><%= resource.name %></td>
                    <td class="whitespace-nowrap px-2 py-2 text-sm text-gray-900"><%= resource.app %></td>
                    <td class="whitespace-nowrap px-2 py-2 text-sm text-gray-900"><%= resource.plan %></td>
                    <%= if resource.organization do %>
                        <td class="whitespace-nowrap px-2 py-2 text-sm text-gray-900">
                            <a href={Routes.organization_path(@conn, :show, resource.organization)} title={resource.organization.id} class="underline"><%= resource.organization.name %></a>
                        </td>
                        <td class="whitespace-nowrap px-2 py-2 text-sm text-gray-900">
                            <%= for project <- resource.organization.projects do %>
                                <a href={Routes.elm_path(@conn, :project_show, resource.organization, project)} title={project.id} class="underline"><%= project.name %></a>
                            <% end %>
                        </td>
                    <% else %>
                        <td class="whitespace-nowrap px-2 py-2 text-sm text-gray-900"></td>
                        <td class="whitespace-nowrap px-2 py-2 text-sm text-gray-900"></td>
                    <% end %>
                    <td class="whitespace-nowrap px-2 py-2 text-sm text-gray-900">
                        <%= if resource.deleted_at do %>
                            Deleted at <%= resource.deleted_at %>
                        <% else %>
                            <a href="#" class="underline cursor-pointer resource-login" data-id={resource.id} data-app={resource.app}>login</a> •
                            <a href={Routes.heroku_path(@conn, :delete, resource.id)} method="delete" class="underline cursor-pointer">delete</a>
                        <% end %>
                    </td>
                </tr>
            <% end %>
        </tbody>
    </table>
    <script>
        document.querySelectorAll('a[method]').forEach(action => {
            action.addEventListener('click', (event) => {
                event.preventDefault()
                fetch(event.target.getAttribute('href'), {
                    method: event.target.getAttribute('method'),
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Basic ${btoa(`<%= @heroku.addon_id %>:<%= @heroku.password %>`)}`
                    }
                }).then(() => document.location.reload(true), err => console.error(err))
            })
        })
        document.querySelectorAll('.resource-login').forEach(action => {
            action.addEventListener('click', (event) => {
                event.preventDefault()
                resourceId.value = event.target.getAttribute('data-id')
                app.value = event.target.getAttribute('data-app')
                computeToken().then(() => loginForm.submit())
            })
        })
    </script>
</div>
